<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property integer $id
 * @property integer $parentID
 * @property integer $createddate
 * @property integer $modifieddate
 * @property integer $sort
 * @property integer $enabled
 * @property integer $deleted
 */
class Category extends CActiveRecord
{
  /**
   * Returns the static model of the specified AR class.
   * @param string $className active record class name.
   * @return Category the static model class
   */

  public $name;
  public $name2;
  public $languageID;
  public $thumbnails = array(
    array('250','240'),
    array('90','85')
  );
 	
  public static function model($className=__CLASS__)
  {
    return parent::model($className);
  }
  
  /**
   * @return string the associated database table name
   */
  public function tableName()
  {
    return '{{category}}';
  }
  
  /**
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
    array('name', 'required'),
    array('image', 'required', 'on' => 'create'),
    array('image', 'file', 'types' => 'jpg, jpeg, gif, png', 'allowEmpty' => true),
    array('createddate, modifieddate, sort, enabled, deleted', 'numerical', 'integerOnly'=>true),
    // The following rule is used by search().
    // Please remove those attributes that should not be searched.
    array('id, createddate, modifieddate, sort, enabled, deleted', 'safe', 'on'=>'search'),
    );
  }
  
  /**
   * @return array relational rules.
   */
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
  	  'categoryLangs' => array(self::HAS_MANY, 'CategoryLang', 'categoryID'),
      'products' => array(self::HAS_MANY, 'Product', 'categoryID'),
    );
  }
  
  /**
   * @return array customized attribute labels (name=>label)
   */
  public function attributeLabels()
  {
    return array(
  		'id' => 'ID',
  	  'name' => Yii::t('default', 'Category'),
      'image' => Yii::t('default', 'Image'), 
  		//'parentID' => Yii::t('default', 'Parent'),
  		'createddate' => Yii::t('default', 'Createddate'),
  		'modifieddate' => Yii::t('default', 'Modifieddate'),
  		'sort' => Yii::t('default', 'Sort'),
  		'enabled' => Yii::t('default', 'Enabled'),
  		'deleted' => 'Deleted',
    );
  }
  
  protected function beforeSave() {
    if($this->isNewRecord) {
      $this->createddate = time();
    }
    $this->modifieddate = time();
    return parent::beforeSave();
  }
  /** Make dropdown for category
   * @author Kieu Diem
   */
  public function getName($id) {
    $name = Yii::app()->db->createCommand()
    ->select('cl.name')
    ->from('tbl_category as t')
    ->join('tbl_category_lang as cl', 'cl.categoryID = t.id')
    ->where('t.deleted = 0 AND t.id = ' . $id)
    ->queryRow();
    if(!empty($name)) {
      return $name['name'];
    }
    return '--';
  }
  
  public function getCategories($list = '')
  {
    $array = array();
    $category = Yii::app()->db->createCommand()
    ->select('t.id, cl.name, t.enabled')
    ->from('tbl_category as t')
    ->join('tbl_category_lang as cl', 'cl.categoryID = t.id')
    ->where('t.enabled = 1 AND t.deleted = 0 AND cl.languageID="'.Yii::app()->session['language'].'"')
    ->order('t.sort')
    ->queryAll();
     
    if ($list == 'list') {
      return $category;
    }
    if(!empty($category)) {
      foreach ($category as $c) {
        $array[$c['id']] = $c['name'];
      }
    }
    return $array;
  }
  
  public function getDropdownCategory($first = '')
  {
    $array = array();
    $category = Category::model()->findAllByAttributes(array('deleted'=>0), array('order'=>'sort'));
    //$array[0] = ($first == '') ? '-- ' . Yii::t('default', 'Root') . ' --' : $first;
    if (!empty($category)) {
      //$this->getChildren(0, '', $array);
      foreach ($category as $cat) {
        $name = CategoryLang::model()->findByAttributes(array('categoryID'=>$cat->id, 'languageID'=>Yii::app()->session['language']));
   	    if (!empty($name)) {
          $name = $name->name;
        }
        $array[$cat->id] = $name;
      }
    }
    return $array;
  }
  
  public function getChildren($parentID, $level, &$array)
  {
    $category = Category::model()->findAllByAttributes(array('parentID'=>$parentID,'deleted'=>0));
    foreach ($category as $item) {
      $name = CategoryLang::model()->findByAttributes(array('categoryID'=>$item->id, 'languageID'=>Yii::app()->session['language']));
      if (!empty($name)) {
        $name = $name->name;
      }
      $array[$item->id] = $level.$name;
      $this->getChildren($item->id, $level.'--', $array);
    }
  }
 	
  public function getCategoryFile($catID, $w, $h)
  {
    $cat = Category::model()->findByPk($catID);
    
    $image = 'no_image.jpg';
    if (!empty($cat) && $cat->image != '') {
      $file = File::model()->findByPk($cat->image);
      if (!empty($file) && file_exists(Yii::app()->basePath . "/../upload/category/thumbs_$w"."x"."$h/" . $file->filesaved)) {
        $image = $file->filesaved;
      }
    }
    return $image;
  }
  
  public function getCategoryImage($catID, $w, $h)
  {
    $linkfile = $this->getCategoryFile($catID, $w, $h);
    $image    = CHtml::image(Yii::app()->baseUrl . "/upload/category/thumbs_$w" . "x" . "$h/$linkfile");
    return $image;
  }
 	/**
 	 * Retrieves a list of models based on the current search/filter conditions.
 	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
 	 */
  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
    $criteria=new CDbCriteria;
    $criteria->together = true;
    $criteria->select = 't.id, l.name, t.createddate, t.modifieddate, t.enabled';
    $criteria->join = 'JOIN tbl_category_lang l ON t.id=l.categoryID';
    $criteria->condition = 't.deleted=0 AND l.languageID="'.Yii::app()->session['language'].'"';
    $criteria->compare('id',$this->id);
    $criteria->compare('enabled',$this->enabled);
    $criteria->order = 'sort ASC';
    
    return new CActiveDataProvider($this, array(
  		'criteria'=>$criteria,
  	  'sort'=>array(
        'attributes'=>array(
          'name'=>array(  
            'asc'=>'l.name',
            'desc'=>'l.name DESC',
          ),
          '*',
        ),
      ),
      'pagination' => array(
        'pageSize' => Yii::app()->user->getState('pageSize', 10)
      )
    ));
  }
}